package com.dy.lock.screen.api.servlet;

import java.io.IOException;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;

import com.dy.lock.screen.api.constants.Constant;
import com.dy.lock.screen.api.scoket.Head;
import com.dy.lock.screen.api.scoket.SocketDTO;
import com.dy.lock.screen.api.scoket.TransmissionCode;
import com.dy.lock.screen.api.server.HttpServerStartMain;
import com.dy.lock.screen.api.utils.CommonUtil;
import com.dy.lock.screen.api.utils.IpUtil;
import com.dy.lock.screen.api.utils.MD5Util;
import com.dy.lock.screen.api.utils.ServletUtil;
import com.dy.lock.screen.api.vo.CustomerBlacklistVo;
import com.dy.lock.screen.api.vo.ResultVo;
import com.dy.lock.screen.api.vo.UserResultVo;
import com.google.gson.Gson;

/**
 * 加入黑名单
 * 
 * @description
 * @author
 * @date
 */
public class JoinBlacklistServlet extends SuperServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private static Logger log = Logger.getLogger(JoinBlacklistServlet.class);
	private static Gson gson = CommonUtil.gson();

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		req.setAttribute("org.eclipse.jetty.server.Request.queryEncoding",
				"UTF-8");
		resp.setContentType("text/html;charset=UTF-8");
		resp.setStatus(HttpServletResponse.SC_OK);

		// 拉黑人的用户id
		String blackCustomer = req.getParameter("userId");
		// 被加入黑名单的用户id
		String beBlackedCustomer = req.getParameter("beBlackedCustomer");

		// 校验密文
		String sign = req.getParameter("sign");

		log.info("加入黑名单：sign：" + sign + "，blackCustomer：" + blackCustomer
				+ "，beBlackedCustomer：" + beBlackedCustomer);
		boolean check = super.checkUser(req, resp);
		if (!check) {
			return;
		}
		boolean flag = this.validateData(sign, blackCustomer,
				beBlackedCustomer, resp, req);
		if (flag) {// 数据校验成功
			try {
				CustomerBlacklistVo vo = new CustomerBlacklistVo();
				vo.setBlackCustomer(blackCustomer);
				vo.setBeBlackedCustomer(beBlackedCustomer);
				SocketDTO dto = sendMessage(vo, req);
				Head head = dto.getHead();
				String resCode = head.getResponseCode();
				// String resMsg = head.getResponseMessage();
				String body = dto.getBody();
				ResultVo ri = new ResultVo();
				if (TransmissionCode.SUCCESS.getCode().equals(resCode)) {
					// 把service中返回的信息转成对应的json格式字符串，返回给接口调用者
					if (StringUtils.isNotBlank(body)) {
						boolean result = gson.fromJson(body, Boolean.class);
						if (result) {
							ri.setCode(Constant.SUCCESS);
							ri.setStatus(Constant.TRUE);
							ServletUtil.writeResJsonStr(resp, gson.toJson(ri));
						} else {
							ServletUtil.writeErrorStr(resp);
						}
					} else {
						ServletUtil.writeErrorStr(resp);
					}
				} else if (TransmissionCode.CUSTOMER_JOIN_BLACKLIST.getCode()
						.equals(resCode)) {
					log.error("内部通信，" + head.getResponseMessage());
					ri.setCode(Constant.JOINED_BLACKLIST);
					ri.setStatus(Constant.FALSE);
					ServletUtil.writeResJsonStr(resp, gson.toJson(ri));
				} else {
					log.error("内部通信异常，" + head.getResponseMessage());
					ServletUtil.writeErrorStr(resp);
				}
			} catch (Exception e) {
				log.error("异常信息", e);
				// 异常情况，也把对应异常信息的json格式字符串返回给接口调用者
				ServletUtil.writeErrorStr(resp);
			}
		}
	}

	/**
	 * 向service服务发送请求
	 * 
	 * @param vo
	 * @param req
	 * @return
	 */
	private SocketDTO sendMessage(CustomerBlacklistVo vo, HttpServletRequest req) {
		Head head = new Head();
		head.setRequestId(UUID.randomUUID().toString());
		head.setServiceCode(Constant.JOIN_BLACKLIST);
		head.setIp(IpUtil.getIpAddr(req));
		head.setUserId("api");
		return super.send(head, vo);
	}

	/**
	 * 数据校验合法性
	 * 
	 * @param userId
	 * @param sign
	 * @param resp
	 * @param req
	 * @return
	 * @throws IOException
	 */
	private boolean validateData(String sign, String blackCustomer,
			String beBlackedCustomer, HttpServletResponse resp,
			HttpServletRequest req) throws IOException {
		UserResultVo ri = new UserResultVo();
		boolean result = false;
		if (StringUtils.isEmpty(beBlackedCustomer)) {
			log.info("被拉黑人用户编号为空!!!");
			ri.setCode(Constant.BE_BLACKED_USER_IS_NULL);
			ri.setStatus(Constant.FALSE);
			ServletUtil.writeResJsonStr(resp, gson.toJson(ri));
			return false;
		} else if (StringUtils.isEmpty(sign)) {
			log.info("签名字符串为空!!!");
			ri.setCode(Constant.SIGN_IS_NULL);
			ri.setStatus(Constant.FALSE);
			ServletUtil.writeResJsonStr(resp, gson.toJson(ri));
			return false;
		} else {
			String key = HttpServerStartMain.getValue("dou.yang.key");
			StringBuilder builder = new StringBuilder();
			builder.append("beBlackedCustomer");
			builder.append(beBlackedCustomer);
			builder.append("userId");
			builder.append(blackCustomer);
			builder.append("key");
			builder.append(key);

			String data = builder.toString();

			boolean checked = MD5Util.checkMD5Signature(data, sign);
			if (checked) {
				result = true;
			} else {
				log.info("数字签名失败！！！");
				ri.setCode(Constant.CHECK_SIGN_FAIL);
				ri.setStatus(Constant.FALSE);
				ServletUtil.writeResJsonStr(resp, gson.toJson(ri));
				return false;
			}
		}

		return result;
	}
}
